import cTitle from "components/title";
import couponLis from "./components/couponLis.vue"
import couponCell from "./components/couponCell.vue"
import BScroll from "better-scroll";
import { scrollMixin } from "../../utils/mixin"; //引入加载更多
export default {
  mixins: [scrollMixin],
  data() {
    return {
      toi: this.fun.getKeyByI(),
      selected: "1",
      pagesize: 1,
      //待使用
      wait_used: [],
      used: [],

      goload: true,
      isLoadMore: true,
      page: 1,
      total_page: 0,
      isPresenter: false,
      // showPresenter: false,
      presenter_data: {},
      recharge_search: '',
      timeoutId: null,
      nickname: null,
      types: [],
      // types:['全部','平台','门店','酒店','指定商品','分类商品','兑换卷','满减卷','折扣卷','快过期'],
      typesIndex: 0,
      pjh: 1,
      share_coupon: false,
      write_off_coupon: false,
      center_show: false,
      combine_show:'',
      // 删除按钮
      deleteShow:true,

      //优化功能
      couponTabs:[
        {
          title:'待使用',
          value:1,
        },
        {
          title:'已过期',
          value:2,
        },
        {
          title:'已使用',
          value:3,
        }
      ],
      higherIndex:'',
      couponScroll:"",
      coThemeColor:'',
      tabIndex:0
    };
  },
  methods: {
    initScroll() {
      if (this.types.length > 0) {
        this.couponScroll = new BScroll(this.$refs.handpickList, {
          scrollX: true,
          click: true
        });
      }
    },
    showCoupon() {
      this.$nextTick(() => {
        if (!this.couponScroll) {
          this.initScroll();
        } else {
          this.couponScroll.refresh();
        }
      });
    },
    // 展开更多折叠的优惠券
    tapMoreList(item, ind) {
      this.higherIndex = ind;
      console.log(item.can_spreadShow_list, '展开更多折叠的优惠券')
      if (!item.can_spreadShow) {
        console.log(item.can_spreadShow_list, 'can_spreadShow_list')
        if (item.can_spreadShow_list && item.can_spreadShow_list.length > 0) {
          this.$set(this.wait_used[ind], 'can_spreadShow', true)
          return
        }
        this.getCouponList(item.coupon_id, ind)
      }
    },
    closeMoreList(item, ind) {
      this.$set(this.wait_used[ind], 'can_spreadShow', false)
    },
    getCouponList(cid, ind) {
      $http
        .get(
          "coupon.member-coupon.get-time-spread-coupon",
          { coupon_id: cid, coupon_type: this.typesIndex },
          "正在获取"
        )
        .then(
          response => {
            if (response.result == 1) {
              this.$set(this.wait_used[ind], 'can_spreadShow_list', response.data)
              this.$set(this.wait_used[ind], 'can_spreadShow', true)
            } else {
              this.$dialog.alert({ message: response.msg });
            }
          }
        );
    },
    initData() {
      this.wait_used = [];
      this.page = 1;
      this.goload = true;
      this.total_page = 0;
      this.allLoaded = false;
      this.isLoadMore = true;
      this.typesIndex = 0;
      this.tabIndex = 0;
      this.isPresenter = false;
    },
    goDetail(data) {
      let {item} = data || {};
      if(!item.is_effective) {
        //待生效不跳转详情
        this.$toast(`生效时间：${item.effective_time_str}`);
        return
      }
      if(item.can_spread || this.selected == 2 || this.selected == 3){
        // 折叠显示展开收起点击不跳转详情
        return
      }
      // let that = this;
      this.$router.push(this.fun.getUrl("coupon_v2_detail", {
        id: item.id,
        combine_show: this.combine_show,
        combine: item.combine
      }));
    },
    toStore() {
      this.$router.push(this.fun.getUrl("couponStore", { myparent: this }));
    },
    goHome() {
      this.$router.push(this.fun.getUrl("home"));
    },
    //切换优惠券状态列表
    switchItem() {
      this.initData();
      this.getNetData(this.selected, this.typesIndex);
    },
    setTypesIndex(ind,item) {
      if (this.tabIndex == ind) {
        return;
      }
      this.tabIndex = ind;
      this.typesIndex = item.id;
      this.getNetData(this.selected, this.typesIndex);
    },
    colorFin(a) { //处理主题色
      a = a.substring(1);
      a = a.toLowerCase();
      let b = new Array();
      for (let x = 0; x < 3; x++) {
        b[0] = a.substr(x * 2, 2);
        b[3] = "0123456789abcdef";
        b[1] = b[0].substr(0, 1);
        b[2] = b[0].substr(1, 1);
        b[20 + x] = b[3].indexOf(b[1]) * 16 + b[3].indexOf(b[2]);
      }
      return b[20] + "," + b[21] + "," + b[22];
    },
    //发起http请求
    getNetData(type, typesIndex) {
      var that = this;
      $http
        .get(
          "coupon.member-coupon.coupons-of-member-by-status-v2",
          { status_request: type, page: 1, coupon_type: typesIndex,basic_info: 1 },
          "正在获取"
        )
        .then(
          response => {
            if (response.result == 1) {
              let themeColor = response.basic_info?.theme_color;
              this.coThemeColor = this.colorFin(themeColor) || this.colorFin('#F15353');
              this.isLoadMore = true;
              this.page = 1;
              var myData = response.data;
              this.showCoupon();
              this.total_page = response.data.data.last_page;
              this.isPresenter = response.data.set.transfer;
              this.center_show = response.data.set.center_show;
              this.types = response.data.search_array;
              this.deleteShow = response.data.set.delete_show;
              let couponList = myData.data.data || [];
              !this.fun.isTextEmpty(myData.write_off_coupon)?this.write_off_coupon = myData.write_off_coupon:this.write_off_coupon = false;
              !this.fun.isTextEmpty(myData.share_coupon)?this.share_coupon = myData.share_coupon:this.share_coupon = false;
              !this.fun.isTextEmpty(myData.combine_show)?this.combine_show = myData.combine_show:this.combine_show = false;
              this.wait_used = couponList;
            } else {
              that.$dialog.alert({ message: response.msg });
            }
          },
          function (response) {
            // error callback
          }
        );
    },
    getMoreData() {
      var that = this;
      this.isLoadMore = false; // 防止多次请求分页数据
      if (this.page >= this.total_page) {
        return;
      } else {
        this.page = this.page + 1;
        $http
          .get(
            "coupon.member-coupon.coupons-of-member-by-status-v2",
            {
              status_request: this.selected,
              page: this.page,
              coupon_type: this.typesIndex,
            },
            "正在获取更多"
          )
          .then((response) => {
            this.isPresenter = response.data.set.transfer;
            this.isLoadMore = true;
            if (response.result == 1) {
              var myData = response.data;
              let couponList = myData.data.data || [];
              this.wait_used = this.wait_used.concat(couponList); //数组拼接
            } else {
              that.page = that.page - 1;
              return;
            }
          },
            function (response) {
              // error callback
            }
          );
      }
    },
    //子组件事件
    delItem(data) {
      let {item,index} = data || {};
      this.$dialog.confirm({
        title:'提示',
        message: `是否删除优惠券${item.belongs_to_coupon?.name}`,
      })
        .then(() => {
          // on confirm
          if(this.selected !== 1) {
            this.$set(this.wait_used[index], 'num', 1)
          }

          this.delteteItem(item,index,this.higherIndex);
        })
        .catch(() => {
          // on cancel
        });
    },
    delteteItem(item, i,higherIndex) {
      let that = this;
      let json = {
        id: item.id,
        i: this.fun.getKeyByI(),
        type: this.fun.getTyep()
      };

      $http.get("coupon.member-coupon.delete", json, "处理中...").then(
         (response) => {
          if (response.result == 1) {
            //没有多张的情况删除优惠券
            if(!item.can_spreadShow_list && this.wait_used[higherIndex]?.can_spreadShow) {
              //展开的优惠券只有一张的情况下
              if(this.wait_used[higherIndex].can_spreadShow_list[i].num == 1) {
                this.wait_used[higherIndex].can_spreadShow_list.splice(i,1);
                this.$set(this.wait_used[higherIndex], 'can_spreadShow_list', this.wait_used[higherIndex].can_spreadShow_list)
              } else {
                let childNum = this.wait_used[higherIndex].can_spreadShow_list[i].num;
                this.$set(this.wait_used[higherIndex].can_spreadShow_list[i], 'num',--childNum);
              }
              //记录总优惠券下面的张数被删除的数量
              let couponArr = this.wait_used[higherIndex].can_spreadShow_list;
              let num = 0;
              if(couponArr && couponArr.length > 0) {
                couponArr.forEach(element => {
                  num += element.num
                });
              }
              this.$set(this.wait_used[higherIndex], 'can_spreadShow', false)
              this.$set(this.wait_used[higherIndex], 'num', num);

            } else {
              //总优惠券折叠起来，删除一张的数量
              let couponNum = this.wait_used[i].num;
              if(this.wait_used[i].num == 1) {
                this.wait_used.splice(i, 1)
              } else {
                couponNum--
                //判断没有折叠状态优惠券出现多张一样的
                if(this.wait_used[i].can_spreadShow_list) {
                  let childArr = this.wait_used[i].can_spreadShow_list.splice(-1,1);
                  this.$set(this.wait_used[i], 'can_spreadShow_list', childArr);
                }
                this.$set(this.wait_used[i], 'num', couponNum);

              }
            }
            this.$toast('操作成功');
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function (response) {
          console.log(response);
        }
      );
    },
  },
  activated() {
    this.initData();
    this.toi = this.fun.getKeyByI();
    // this.used = [];
    this.wait_used = [];
    this.selected = '1';

    this.getNetData(1, this.typesIndex);
  },
  mounted() { },
  components: { cTitle, couponLis,couponCell }
};
